<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="班级名称">
                <a-input v-model="queryParam.departmentName" placeholder=""/>
              </a-form-item>
            </a-col>

            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>

              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
        <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1" @click="remove()"><a-icon type="delete" />删除</a-menu-item>
            <!-- lock | unlock -->
            <!--<a-menu-item key="2"><a-icon type="lock" />锁定</a-menu-item>-->
          </a-menu>
          <a-button style="margin-left: 8px">
            批量操作 <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :rowSelection="rowSelection"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="departmentCode" slot-scope="text">

          {{text}}
        </span>
        <span slot="departmentName" slot-scope="text">
          {{ text }}
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(selectedRowKeys)">修改</a>
            <a-divider type="vertical" />
            <!--<a @click="handleSub(record)">订阅报警</a>-->
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <step-by-step-modal ref="modal" @ok="handleOk"/>
    </a-card>
  </page-header-wrapper>
</template>

<script>
  import moment from 'moment'
  import { STable, Ellipsis } from '@/components'
  import { getDepartmentList ,saveDepartment,deleteDepartment} from '@/api/department'

  import StepByStepModal from './modules/StepByStepModal'
  import CreateForm from './modules/CreateForm'

  const columns = [
    {
      title: '#',
      scopedSlots: { customRender: 'serial' }
    },
    {
      title: '班级编号',
      dataIndex: 'departmentCode'
    },
    {
      title: '班级名称',
      dataIndex: 'departmentName'
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: '150px',
      scopedSlots: { customRender: 'action' }
    }
  ]



  export default {
    name: 'TableList',
    components: {
      STable,
      Ellipsis,
      CreateForm,
      StepByStepModal
    },
    data () {
      this.columns = columns
      return {
        // create model
        visible: false,
        confirmLoading: false,
        mdl: null,
        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {

        },
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          const requestParameters = Object.assign({}, parameter, this.queryParam)
          console.log('loadData request parameters:', requestParameters)
          return getDepartmentList(requestParameters)
            .then(res => {
              // console.log('查询班级数据',res)
              return res
            })
        },
        selectedRowKeys: [],
        selectedRows: []
      }
    },
    filters: {
      statusFilter (type) {
        return statusMap[type].text
      },
      statusTypeFilter (type) {
        return statusMap[type].status
      }
    },
    created () {
      // getRoleList({ t: new Date() })
    },
    computed: {
      rowSelection () {
        return {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      }
    },
    methods: {
      handleAdd () {
        this.mdl = null
        this.visible = true
      },
      handleEdit (record) {
        this.visible = true
        this.mdl = { ...record }
      },
      handleOk () {
        const form = this.$refs.createModal.form
        this.confirmLoading = true
        form.validateFields((errors, values) => {
          if (!errors) {
            console.log('values', values)
            if (values.departmentId > 0) {
              // 修改 e.g.
              new Promise((resolve, reject) => {

                saveDepartment({
                  "departmentCode":values.departmentCode,
                  "departmentName":values.departmentName,
                  "departmentId":values.departmentId

                }).then(res => {
                  console.log('修改返回数据', res)

                }).catch(err => {
                  this.$message.info(res.msg)
                })
                setTimeout(() => {
                  resolve()
                }, 1000)
              }).then(res => {
                this.visible = false
                this.confirmLoading = false
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                this.$refs.table.refresh()

                this.$message.info('修改成功')
              })
            } else {
              // 新增
              new Promise((resolve, reject) => {
                saveDepartment({
                  "departmentCode":values.departmentCode,
                  "departmentName":values.departmentName,
                  "departmentId":values.departmentId

                }).then(res => {
                  console.log('修改返回数据', res)

                }).catch(err => {
                  this.$message.info(res.msg)
                })
                setTimeout(() => {
                  resolve()
                }, 1000)
              }).then(res => {
                this.visible = false
                this.confirmLoading = false
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                this.$refs.table.refresh()

                this.$message.info('新增成功')
              })
            }
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel () {
        this.visible = false

        const form = this.$refs.createModal.form
        form.resetFields() // 清理表单数据（可不做）
      },
      // handleSub (record) {
      //   if (record.status !== 0) {
      //     this.$message.info(`${record.no} 订阅成功`)
      //   } else {
      //     this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      //   }
      // },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      resetSearchForm () {
        this.queryParam = {
          date: moment(new Date())
        }
      },
      remove () {
        console.log(this.selectedRowKeys)
        console.log(this.selectedRows)
        var departmentIds =   this.selectedRows.map(item => {
          console.log(item.departmentId)
          return item.departmentId
        })
        deleteDepartment({
          departmentIds: departmentIds
        }).then(data => {
          if (data && data.code === 0) {
            console.log('删除返回数据', res)
            this.$message.info(data.msg)
            // 刷新表格
            this.$refs.table.refresh()
          } else {
            this.$message.error(data.msg)
          }
        }).catch(err => {
          this.$message.info('操作错误')
        })

      },
      // 删除
      deleteHandle (id) {
        var userIds = id ? [id] : this.dataListSelections.map(item => {
          return item.userId
        })
        this.$confirm(`确定对[id=${userIds.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/sys/user/delete'),
            method: 'post',
            data: this.$http.adornData(userIds, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {})
      }
    }
  }
</script>
